<?php

	require_once("includes/config.php");
	require_once("includes/functions.php");
	require_once("classes/class.Team.php");
	require_once("classes/class.Field.php");
	require_once("classes/class.User.php");
	require_once("classes/class.Metric.php");
	
	global $db_host, $db_username, $db_password, $db_database;

	$action = strtolower($_GET["action"]);
	$form_id = strtolower($_POST["form_id"]);

	if($action=="logout") {
		
		setcookie("login_username","",time()-3600);			
		setcookie("login_name","",time()-3600);	
		setcookie("login_level",0,time()-3600);
			
		header("location:index.php?page=default");

	}

	if($form_id=="login") {
		
		$login_username = strtolower($_POST["login_username"]);
		$login_password = $_POST["login_password"];
		
		$login_user = new User();
		$login_user->Load($login_username);
		
		$user_password = $login_user->GetPassword();
		$user_name = $login_user->GetName();
		$user_level = $login_user->GetLevel();
		
		if($login_password==$user_password and $user_level>=10) {
			setcookie("login_username",$login_username,time()+3600);			
			setcookie("login_name",$user_name,time()+3600);
			setcookie("login_level",$user_level,time()+3600);
		} else {
			setcookie("login_username","",time()-3600);			
			setcookie("login_name","",time()-3600);
			setcookie("login_level",0,time()-3600);
		}
		
		header("location:index.php?page=default");
		
	}

	if($form_id=="metric") {

		$array_post = $_POST;
		$post_user_id = $_POST["user_id"];
		$post_team_name = $_POST["team_name"];
		$post_datestamp = $_POST["datestamp"];
		
		$array_post_keys = array_keys($array_post);
		
		foreach($array_post_keys as $item) {
		
			if(substr($item,0,6)=="FIELD_") {
			
				$field_name		= substr($item,6);
				$field_value	= $array_post[$item];
				
				$obj_field = new Field();
				$obj_field->Load($field_name);
				
				$field_team_name = $obj_field->GetTeamName();
				
				$value_valid = true;
				
				if($obj_field->GetType()=="NUMBER") {
					if(is_numeric($field_value)==false) {
						$value_valid = false;
					}
				}
				
				if($obj_field->GetType()=="DATE") {
					$field_value = substr($field_value,6,4) . "-" . substr($field_value,3,2) . "-" . substr($field_value,0,2);
				}
			
				/*
				echo $field_name;
				echo ": ";
				echo $field_value;
				echo "<br/>";
				*/
				
				$obj_metric = new Metric();
				$obj_metric->SetUserId($post_user_id);
				$obj_metric->SetTeamName($field_team_name);
				$obj_metric->SetDatestamp($post_datestamp);
				$obj_metric->SetFieldName($field_name);
				$obj_metric->SetValue($field_value);
				if($value_valid==true) {
					$obj_metric->Save();
				}
				$obj_metric = null;
				
				
			}
		
		}
	
	}

?>

<html>
	<head>
		<title>Metrix</title>
		<meta http-equiv="refresh" content="0;URL=index.php?page=default"/>
	</head>
</html>